<template>
  <div>
    <el-main>
      <div class="form_title">商品信息</div>
      <div class="form_content">
        <el-form
          ref="form"
          label-width="80px"
          :model="model"
          :rules="rules"
        >
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="商品分类" prop="categoryName">
                <el-input
                  placeholder="请选择商品分类"
                  v-model="model.categoryName"
                  readonly="readonly"
                  @click.native="handleOpenCategory"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="名称" prop="name">
                <el-input
                  placeholder="请输入名称"
                  v-model="model.name"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="显示名称" prop="displayName">
                <el-input
                  placeholder="请输入显示名称"
                  v-model="model.displayName"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="商品图片" prop="image">
                <el-upload
                  :headers="headerObj"
                  :file-list="model.images"
                  :on-exceed="imageHandleExceed"
                  :on-remove="imageHandleRemove"
                  :on-success="imageHandleSuccess"
                  :limit="10"
                  action="/cloud-backend/admin/upload/upload"
                  list-type="picture-card"
                  accept="image/*">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="价格" prop="price">
                <el-input v-model="model.price" placeholder="请输入价格" style="width: 200px">
                  <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px; color: #1e1e1e">元</i>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="排序" prop="sortIndex">
                <el-input-number v-model="model.sortIndex" :min="1" :max="1000" placeholder="请输入排序"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" :rows="5" v-model="model.remark" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <SelectCommerceCategory
        :show="selectCategoryVisible"
        :searchOnShow="true"
        :categoryId="model.categoryId"
        @selectCategory="handleSelectCategory"
        @clearCategory="handleClearCategory"
        @closeCategory="handleCloseCategory"
      ></SelectCommerceCategory>
    </el-main>
    <el-footer>
      <el-button
        icon="el-icon-close"
        size="small"
        @click="$router.go(-1)"
      >取消</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-check"
        size="small"
        @click="handleSave"
      >保存</el-button
      >
    </el-footer>
  </div>
</template>

<script>
  import SelectCommerceCategory from "@/components/dialog/SelectCommerceCategory.vue"
  import {updateGoods,viewGoods} from "@/api/commerce/goods";
  import {getToken} from "@/utils/auth";
  import {ApiError} from "@/utils/errors";

  export default {
    components: {SelectCommerceCategory},
    data() {
      return {
        headerObj:{},
        selectCategoryVisible: false,
        model: {
          categoryId: null,
          categoryName: null,
          name: null,
          displayName: null,
          images: [],
          price: null,
          sortIndex: 1,
          remark: null
        },
        rules: {
          categoryName: [{ required: true, message: "商品分类必须选择", trigger: "blur" }],
          name: [{ required: true, message: "名称必须填写", trigger: "blur" }],
          displayName: [{ required: true, message: "显示名称必须填写", trigger: "blur" }],
          price: [{ required: true, message: "价格必须填写", trigger: "blur" }],
          sortIndex: [{ required: true, message: "排序必须填写", trigger: "blur" }]
        }
      }
    },
    created() {
      this.headerObj.token = getToken();
      const id = this.$route.query.id;
      this.get(id);
    },
    methods: {
      handleOpenCategory(){
        this.selectCategoryVisible = true;
      },
      handleSelectCategory(row){
        this.model.categoryId = row.data.id;
        this.model.categoryName = row.data.name;
        this.selectCategoryVisible = false;
      },
      handleClearCategory(){
        this.model.categoryId = null;
        this.model.categoryName = null;
        this.selectCategoryVisible = false;
      },
      handleCloseCategory(){
        this.selectCategoryVisible = false;
      },
      get(id){
        const that = this;
        const params = {id:id};
        viewGoods(params).then(res => {
          if (res.status == 200) {
            if (!res.data.success) {
              return this.$message.error(ApiError.msg(res.data.message));
            }
            that.model.id = res.data.data.id;
            that.model.name = res.data.data.name;
            that.model.displayName = res.data.data.displayName;
            that.model.images = JSON.parse(res.data.data.images);
            that.model.images.forEach(function (value) {
              value.url = '/cloud-backend/cos/'+value.path;
            });
            that.model.price = res.data.data.price/100;
            that.model.sortIndex = res.data.data.sortIndex;
            that.model.remark = res.data.data.remark;
            that.model.categoryId = res.data.data.categoryId;
            that.model.categoryName = res.data.data.categoryName;
          }
        });
      },
      imageHandleSuccess: function (response, file) {
        if(response.success){
          this.model.images.push({
            url: file.url,
            name: file.name,
            path: response.data.key,
            uid: file.uid
          });
        }else {
          this.$notify({
            title: '失败',
            message: response.msg,
            type: 'warning'
          });
        }
      },
      imageHandleRemove: function (file) {
        var index = -1;
        index = this.model.images.findIndex(function (text) {
          return text == file;
        });

        if (index != -1) {
          this.model.images.splice(index, 1);
        }
      },
      //上传超过限制
      imageHandleExceed: function () {
        this.$notify({
          title: '失败',
          message: '当前最多上传10个文件',
          type: 'warning'
        });
      },
      handleSave() {
        const that = this;
        this.$refs.form.validate(valid => {
          if (!valid) {
            return;
          }
          const data = JSON.parse(JSON.stringify(this.model));
          data.images = JSON.stringify(data.images);
          data.price = data.price*100;
          updateGoods(data).then(res => {
            if (res.status == 200) {
              if (!res.data.success) {
                return this.$message.error(ApiError.msg(res.data.message));
              }
              this.$message.success("修改商品成功");
              that.$router.go(-1);
            }
          });
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .form_title {
    padding-bottom: 20px;
    font-size: 16px;
    font-weight: 700;
    color: rgba(0, 0, 0, 0.85);
  }
  .form_content {
    padding-right: 16px;
  }
  .input_suffix {
    display: inline-block;
    padding: 0 6px;
  }
  .el-divider {
    margin: 6px 0 16px;
  }
  .add_new_batch {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 16px;
    height: 45px;
    border: 1px dashed #d9d9d9;
    cursor: pointer;
    color: #8c939d;
  }
  .batch_block {
    margin-top: 16px;
  }
  .batch_block:first-child {
    margin-top: 0;
  }
  @import "@/styles/full-form";
  @import "@/styles/common-table";
</style>
